
<template>
  <div class="yy-equipment-parameter-manage">
    <!--列表-->
    <div class="yy-equipment-parameter-list" v-show="type=='list'">
      <Card>
        <p slot="title">
          <Icon type="md-list" />
          设备台账
        </p>
        <Form ref="formInline" :model="formSearch"  inline>
            <FormItem prop="user">
              <Input type="text" v-model="formSearch.dName" placeholder="设备名称"></Input>
            </FormItem>
            <FormItem prop="user">
              <Input type="text" v-model="formSearch.spec" placeholder="规格型号"></Input>
            </FormItem>
            <FormItem prop="user">
              <Input type="text" v-model="formSearch.dNewNum" placeholder="设备编码"></Input>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.daNum" @on-change="changeHospitalArea(formSearch.daNum)" placeholder="请选院区">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in hospitalArea" :value="item.daNum" :key="index">{{item.daName}}</Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.ddNum" placeholder="请选择部门">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in department" :value="item.ddNum" :key="index">{{item.ddName}}</Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.dsNum" @on-change="changeKnowledgeClassification(formSearch.dsNum)" placeholder="请选择设备系统">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in knowledgeClassification" :value="item.dsNum" :key="index">
                  {{item.dsName}}
                </Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.dcNum" placeholder="请选择设备类别">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in equipmentCategory" :value="item.dcNum" :key="index">{{item.dcName}}</Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.status" placeholder="请选择设备状态">
                <Option value="">请选择</Option>
                <Option value="1">正常</Option>
                <Option value="2">维修</Option>
                <Option value="3">报废</Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.storageNum" placeholder="请选择后勤部门">
                <Option value="">请选择</Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.storageNum" placeholder="请选择维修部门">
                <Option value="">请选择</Option>
              </Select>
            </FormItem>
            <FormItem prop="user">
              <DatePicker type="date" placeholder="安装起始时间" style="width: 200px"  v-model="formSearch.st" :options="startTimeOption" @on-change="onStartTimeChange"></DatePicker>
            </FormItem>
            <FormItem prop="user">
              <DatePicker type="date" placeholder="安装结束时间" style="width: 200px" v-model="formSearch.et" :options="endTimeOption" @on-change="onEndTimeChange"></DatePicker>
            </FormItem>
          </FormItem>
            <FormItem>
              <Button type="primary" @click="handleSearch()">查询</Button>
            </FormItem>
             <FormItem>
              <Button type="primary" @click="handleReset" class="button">重置</Button>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleAdd()">新增</Button>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleExecl()">导出</Button>
            </FormItem>
        </Form>
        <Table :columns="columns" :data="data" ></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
              <Page :total="page.total" :page-size="page.pageSize" :current="1" @on-change="changePage" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
    <!--详情-->
    <div class="yy-goods-manage-details" v-show="type=='details'">
       <Card>
        <p slot="title">
          <Icon type="md-paper"/>
          查看详情
        </p>
        <p slot="extra">
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="details">
          <p class="details-title"><span>设备编码:</span>{{currentData.dNewNum}}</p>
          <p class="details-title"><span>设备名称:</span>{{currentData.dName}}</p>
          <p class="details-title"><span>拼音简码:</span>{{currentData.dPy}}</p>
          <p class="details-title"><span>出厂编号:</span>{{currentData.factoryNum}}</p>
          <p class="details-title"><span>院区:</span>{{currentData.daName}}</p>
          <p class="details-title"><span>部门:</span>{{currentData.ddName}}</p>
          <p class="details-title"><span>设备系统:</span>{{currentData.dsName}}</p>
          <p class="details-title"><span>设备类别:</span>{{currentData.dcName}}</p>
          <p class="details-title"><span>产地:</span>{{currentData.devOrigin}}</p>
          <p class="details-title"><span>状态:</span>{{currentData.status}}</p>
          <p class="details-title"><span>安装位置:</span>{{currentData.installAddress}}</p>
          <p class="details-title"><span>品牌:</span>{{currentData.brand}}</p>
          <p class="details-title"><span>规格型号:</span>{{currentData.spec}}</p>
          <p class="details-title"><span>供应商:</span>{{currentData.supName}}</p>
          <p class="details-title"><span>生产商:</span>{{currentData.prodName}}</p>
          <p class="details-title"><span>使用年限(年):</span>{{currentData.life}}</p>
          <p class="details-title"><span>保修期年(年):</span>{{currentData.maintain}}</p>
          <p class="details-title"><span>购置日期:</span>{{currentData.purDate}}</p>
          <p class="details-title"><span>安装日期:</span>{{currentData.installDate}}</p>
          <p class="details-title"><span>设备原值(元):</span>{{currentData.devMoney}}</p>
          <p class="details-title"><span>描述:</span>{{currentData.description}}</p>
          <p class="details-title"><span>技术资料:</span>{{currentData.docPath}}
            <div class="contract-upload-list" v-for="item in uploadList" :key="item.url">
              <div class="contract-upload-list-text">文件</div>
              <div class="contract-upload-list-cover">
                <Icon type="ios-cloud-download-outline" @click.native="handleView(item)"></Icon>
              </div>
            </div>
          </p>
          <p class="details-title"><span>二维码:</span></p>
          <img class="contract-upload-list-qrcode" :src="imgUrl" alt="">
        </div>
      </Card>
    </div>
    <!--添加/编辑-->
    <div class="yy-goods-manage-add-edit"  v-show="(type=='add' || type=='edit')">
      <Card>
        <p slot="title">
          <template v-if="type=='add'"> 
            <Icon type="md-create"/> 新增
          </template>
          <template v-if="type=='edit'"> 
            <Icon type="md-document"/>编辑
          </template>
        </p>
        <p slot="extra" >
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="editForm">
          <Form ref="editForm" :model="editFormInLine" :rules="editFormRuleInline" :label-width="100" @keydown.native.enter.prevent ="handleSubmit">
            <FormItem label="设备编码"  prop="dNewNum">
              <Input v-model="editFormInLine.dNewNum" placeholder="请输入设备编码"></Input>
            </FormItem>
            <FormItem label="设备名称" prop="dName">
              <Input v-model="editFormInLine.dName" placeholder="请输入设备名称"></Input>
            </FormItem>   
            <FormItem label="拼音简码" prop="dPy">
              <Input v-model="editFormInLine.dPy" placeholder="请输入拼音简码"></Input>
            </FormItem>      
            <FormItem label="出厂编号" prop="factoryNum">
              <Input v-model="editFormInLine.factoryNum" placeholder="请输入出厂编号"></Input>
            </FormItem>
            <FormItem label="院区" prop="daNum">
              <Select class="select" v-model="editFormInLine.daNum" @on-change="changeHospitalArea(editFormInLine.daNum)" placeholder="请选院区">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in hospitalArea" :value="item.daNum" :key="index">{{item.daName}}</Option>
              </Select>
            </FormItem>
            <FormItem label="部门 " prop="ddNum">
              <Select class="select" v-model="editFormInLine.ddNum" placeholder="请选择部门">
                <Option value="0">请选择</Option>
                <Option v-for="(item,index) in department" :value="item.ddNum" :key="index">{{item.ddName}}</Option>
              </Select>
            </FormItem>
            <FormItem label="设备系统" prop="dsNum">
              <Select class="select" v-model="editFormInLine.dsNum" @on-change="changeKnowledgeClassification(editFormInLine.dsNum)" placeholder="请选择设备系统">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in knowledgeClassification" :value="item.dsNum" :key="index">
                  {{item.dsName}}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="设备类别 " prop="dcNum">
              <Select class="select" v-model="editFormInLine.dcNum" placeholder="请选择设备类别">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in equipmentCategory" :value="item.dcNum" :key="index">{{item.dcName}}</Option>
              </Select>
            </FormItem>
            <FormItem label="产地" prop="devOrigin">
              <Input v-model="editFormInLine.devOrigin" placeholder="产地"></Input>
            </FormItem>
            <FormItem label="状态 " prop="status">
              <Select class="select" v-model="editFormInLine.status" placeholder="请选择设备状态">
                <Option value="">请选择</Option>
                <Option :value=1>正常</Option>
                <Option :value=2>维修</Option>
                <Option :value=3>报废</Option>
              </Select>
            </FormItem>
            <FormItem label="安装位置" prop="installAddress">
              <Input v-model="editFormInLine.installAddress" placeholder="请输入安装位置"></Input>
            </FormItem>
            <FormItem label="品牌 " prop="brand">
              <Input v-model="editFormInLine.brand" placeholder="品牌"></Input>
            </FormItem>
            <FormItem label="规格型号 " prop="spec">
              <Input v-model="editFormInLine.spec" placeholder="规格型号"></Input>
            </FormItem>
            <FormItem label="供应商 " prop="supName">
              <Input v-model="editFormInLine.supName" placeholder="供应商"></Input>
            </FormItem>
            <FormItem label="生产商 " prop="prodName">
              <Input v-model="editFormInLine.prodName" placeholder="生产商"></Input>
            </FormItem>
            <FormItem label="使用年限（年） " prop="life">
              <Input v-model="editFormInLine.life" placeholder="使用年限（年）"></Input>
            </FormItem>
            <FormItem label="保修期（年） " prop="maintain">
              <Input v-model="editFormInLine.maintain" placeholder="保修期（年）"></Input>
            </FormItem>
            <FormItem label="购置日期 " prop="purDate">
              <Input v-model="editFormInLine.purDate" placeholder="购置日期"></Input>
            </FormItem>
            <FormItem label="安装日期  " prop="installDate">
              <Input v-model="editFormInLine.installDate" placeholder="安装日期"></Input>
            </FormItem>
            <FormItem label="设备原值（元） " prop="devMoney">
              <Input v-model="editFormInLine.devMoney" placeholder="设备原值（元）"></Input>
            </FormItem>
            <FormItem label="描述 " prop="description">
              <Input v-model="editFormInLine.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述" maxlength="50"></Input>
            </FormItem>
            <FormItem label="技术资料 " prop="docPath">
              <Input v-model="editFormInLine.docPath" placeholder="技术资料"></Input>
            </FormItem>
            <FormItem label="上传 " prop="CusName">
              <div class="contract-upload-list" v-for="item in uploadList" :key="item.url">
                <div class="contract-upload-list-text">文件</div>
                <div class="contract-upload-list-cover">
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                </div>
              </div>
              <Upload
                ref="upload"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['pdf','docx','xlsx','jpg','jpeg','png','dwg']"
                :max-size="10240"
                :on-error="handleError"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                multiple
                type="drag"
                action="/api/UploadImg2"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
            <FormItem>
              <Button @click="handleSubmit" type="primary" class="button">提交</Button>
              <Button @click="handleReset" type="primary" class="button">重置</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatArrObjIndex, formatNetTime } from "@/libs/tools";
import i18n from "./locale";
import mixin from "@/mixin/date-mixin";

export default {
  name: "yy-equipment-parameter-manage",
  mixins: [mixin],
  imgUrl: "",
  data() {
    return {
      i18n: i18n,
      currentData: "",
      detailsModal: false,
      type: "list",
      uploadList: [],
      dataCateName: [],
      page: {
        total: 0,
        pageSize: 20
      },
      formSearch: {
        st: "",
        et: "",
        dName: "",
        spec: "",
        daNum: "",
        dsNum: "",
        dcNum: "",
        status: "",
        dNewNum: "",
        userID: ""
      },
      editFormInLine: {
        dName: "",
        dNum: "",
        dPy: "",
        factoryNum: "",
        daNum: "",
        daName: "",
        ddNum: "",
        ddName: "",
        dsNum: "",
        dsName: "",
        dcNum: "",
        dcName: "",
        devOrigin: "",
        status: 1,
        installAddress: "",
        brand: "",
        spec: "",
        supName: "",
        prodName: "",
        life: "",
        maintain: "",
        purDate: "",
        installDate: "",
        devMoney: "",
        description: "",
        dNewNum: "",
        docPath: "",
        userID: ""
      },
      editFormRuleInline: {
        dName: ValidatorRule.require,
        daNum: ValidatorRule.select,
        ddNum: ValidatorRule.select,
        dsNum: ValidatorRule.select,
        dcNum: ValidatorRule.select,
        installAddress: ValidatorRule.require
      },
      columns: [
        {
          title: "设备名称",
          key: "dName"
        },
        {
          title: "设备编码",
          key: "dNewNum"
        },
        {
          title: "规格型号 ",
          key: "spec"
        },
        {
          title: "所属部门 ",
          key: "ddName"
        },
        {
          title: "安装位置 ",
          key: "installAddress"
        },
        {
          title: "设备系统 ",
          key: "dsName"
        },
        {
          title: "设备类别 ",
          key: "dcName"
        },
        {
          title: "保修年限",
          key: "maintain"
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.details(params.index);
                    }
                  }
                },
                "查看"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.delete(params.index, params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: [],
      hospitalArea: [],
      department: [],
      knowledgeClassification: [],
      equipmentCategory: []
    };
  },

  mounted() {
    this.userInfo = this.$store.state.user.userInfo;
    this.initClassification();
    this.initHospitalArea();
    this.handleSearch();
  },

  computed: {},

  methods: {
    //院区选择
    initHospitalArea() {
      let obj = {
        userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getHospitalArea(obj);
    },

    getHospitalArea(obj) {
      API.getHospitalArea(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            this.hospitalArea = data.list;
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    //设备系统分类
    initClassification() {
      let obj = {
        userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getClassification(obj);
    },

    getClassification(obj) {
      API.getClassification(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            this.knowledgeClassification = data.list;
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    changeHospitalArea(num) {
      let obj = {
        daNum: num,
        userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getDepartment(obj);
    },

    //部门选择
    getDepartment(obj, callback) {
      API.getDepartment(obj)
        .then(res => {
          if (res.code == 200) {
            let dataLoc = res.data;
            this.department = dataLoc.list;
          }
          if (callback) {
            callback();
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    changeKnowledgeClassification(num) {
      let obj = {
        dsNum: num,
        userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getEquipmentCategory(obj);
    },

    //获取设备类别
    getEquipmentCategory(obj, callback) {
      API.getEquipmentCategory(obj)
        .then(res => {
          if (res.code == 200) {
            let dataLoc = res.data;
            this.equipmentCategory = dataLoc.list;
          }
          if (callback) {
            callback();
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    handleSearch() {
      let obj = this.formSearch;
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.formSearch = obj;
      this.getList(obj);
    },

    changePage(pageNum) {
      let obj = this.formSearch,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    getList(obj) {
      API.getList(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            if (data != null) {
              this.page.total = data.total;
              this.page.pageSize = data.pageSize;
              this.data = data.list;
            } else {
              this.$Message.success({ content: "暂无数据！" });
              this.data = [];
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    goBack() {
      this.type = "list";
    },

    handleAdd() {
      this.type = "add";
      this.currentData = "";
      this.uploadList = [];
      this.handleReset();
    },

    details(index) {
      this.type = "details";
      this.uploadList = [];
      this.currentData = _.clone(this.data[index]);
      this.imgUrl =
        "http://218.70.30.134:32537/ApService/showQR.aspx?asc=" +
        this.currentData.dNum;
      let obj = {
        url: this.currentData.docPath
      };
      this.uploadList.push(obj);
      if (this.currentData.status == "1") {
        this.currentData.status = "正常";
      }
      if (this.currentData.status == "2") {
        this.currentData.status = "维修";
      }
      if (this.currentData.status == "3") {
        this.currentData.status = "报废";
      }
    },

    edit(index) {
      this.type = "edit";
      this.handleReset();
      this.uploadList = [];
      this.currentData = this.data[index];
      this.editFormInLine = _.clone(this.currentData);
      this.editFormInLine.userID = this.currentData.userID;
      delete this.editFormInLine.ddNum;
      delete this.editFormInLine.dcNum;
      //console.log(this.editFormInLine.status);
      let objA = {
        daNum: this.currentData.daNum,
        //userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getDepartment(objA, () => {
        this.editFormInLine.ddNum = this.currentData.ddNum;
        //console.log(this.editFormInLine.ddNum);
      });

      let objB = {
        dsNum: this.currentData.dsNum,
        //userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getEquipmentCategory(objA, () => {
        this.editFormInLine.dcNum = this.currentData.dcNum;
      });

      let obj = {
        url: this.currentData.docPath
      };
      this.uploadList.push(obj);
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            id: "",
            dNum: "",
            userID: ""
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              console.log(err);
              this.$Message.error("请求异常！");
            });
        }
      });
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.formSearch.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.formSearch.pageNum !== 1
      ) {
        this.formSearch.pageNum = this.formSearch.pageNum - 1;
      }
      let obj = this.formSearch;
      this.getList(obj);
    },

    handleSubmit() {
      this.editFormInLine = this.addUploadToData(this.editFormInLine);
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.type == "edit") {
            this.editSubmit(this.editFormInLine);
          } else {
            this.addSubmit(this.editFormInLine);
          }
        }
      });
      //console.log(this.editFormInLine.docPath)
    },

    addUploadToData(obj) {
      let arr = [];
      for (let i in this.uploadList) {
        arr.push(this.uploadList[i].url);
      }
      if (arr.length > 0) {
        obj.docPath = JSON.stringify(arr);
      } else {
        obj.docPath = "";
      }
      return obj;
    },

    handleReset() {
      this.$refs.editForm.resetFields();
      this.$refs.formInline.resetFields();
    },

    editSubmit(obj) {
      obj.userID = "";
      API.editSubmit(obj)
        .then(res => {
          if (res.code == 200) {
            this.resetList();
            this.$Message.success("修改成功！");
            this.goBack();
          }
        })
        .catch(err => {
          this.$Message.error("修改异常！");
        });
    },

    addSubmit(obj) {
      API.addSubmit(obj)
        .then(res => {
          if (res.code == 200) {
            this.handleSearch();
            this.$Message.success("添加成功！");
            this.goBack();
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    handlePrint() {
      window.print();
    },

    handleExecl() {
      alert("后台直接导出EXECL文件！");
    },

    /*************************图片相关***********************/
    handleView(obj) {
      window.location.href = obj.url;
    },

    handleError(err, file) {
      console.log("handleError", err);
    },

    handleRemove(file) {
      let index = formatArrObjIndex(this.uploadList, "url", file.url);
      this.uploadList.splice(index, 1);
      //console.log(this.uploadList);
    },

    handleSuccess(res, file) {
      //file.url = file.response.data.url;
      let obj = {
        url: file.response.data.url
      };
      this.uploadList.push(obj);
      //console.log(this.uploadList);
    },

    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc: "文件" + file.name + " 的格式不正确, 请选择正确的格式"
      });
    },

    handleMaxSize(file) {
      this.$Notice.warning({
        title: "上传文件大小限制",
        desc: "文件" + file.name + " 太大,不能超过10M."
      });
    },

    handleBeforeUpload(file) {
      const check = this.uploadList.length < 4;
      if (!check) {
        this.$Notice.warning({
          title: "最多上传4个文件."
        });
      }
      return check;
    }
  }
};
</script>
<style lang="less" >
@import "./yy-equipment-parameter-manage.less";
</style>
